﻿using Infrastructure.Utility.Core.PDF;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using static Org.BouncyCastle.Math.EC.ECCurve;

namespace Infrastructure.Utility.Core
{
    /// <summary>
    ///v1版本电子凭证
    /// </summary>
    public abstract class PdfBaseBuilder : TemplatePdfBaseBuilder
    {
        protected PdfBaseBuilder(OrderInfo orderInfo, CustomerInfo customerInfo, ReceiptInfo receiptInfo, OrderItemInfo orderItemInfo,
                                 FromOrderInfo refundInfo, ElecCertConfig config, string pathSeal)
            : base(orderInfo, customerInfo, receiptInfo, orderItemInfo, refundInfo, config, pathSeal)
        {

        }

        #region  通用最顶部标题生成

        protected override Document GetHeader()
        {



            if (Config.Category?.ToLower() == "servicecategory" || OrderInfo.OrderCategory?.ToLower() == "servicecategory")
            {
                //服务费
                return base.GetHeader();
            }

            var par2 = new Paragraph(new Chunk("缴费电子凭证", font));
            par2.Alignment = Element.ALIGN_CENTER;
            document.Add(par2);
            var No = new Paragraph(new Chunk($"No:{Regex.Replace(OrderInfo.OrderNumber ?? "  ", @"^[A-Za-z]+", string.Empty)}"));
            No.Alignment = Element.ALIGN_RIGHT;
            No.SpacingBefore = -17;
            No.SpacingAfter = 5;
            document.Add(No);
            return document;
        }
        #endregion

        #region 通用客户信息首行 【姓名，性别，电话，居住城市】
        /// <summary>
        /// 通用客户信息首行 【姓名，性别，电话，居住城市】
        /// </summary>
        /// <param name="table">table表格</param>
        protected override void GetCustomerInfo()
        {
            if (Config.Version == 2)//最新模板PDF
            {
                base.GetCustomerInfo();
                return;
            }
            var cellList = new List<PdfPCell>()
            {
                new PdfPCell(new Phrase("姓名", font)){ },
                new PdfPCell(new Phrase(CustomerInfo.Name, font)) ,

                new PdfPCell(new Phrase("性别", font))  ,
                new PdfPCell(new Phrase(CustomerInfo.Gender, font)) ,

                new PdfPCell(new Phrase("手机号", font)) ,
                new PdfPCell(new Phrase(CustomerInfo.Mobile,new Font(baseFont, 11)))  ,

                new PdfPCell(new Phrase("所属城市", font)),
                new PdfPCell(new Phrase(CustomerInfo.City, font))

             };

            for (int i = 0; i < cellList.Count; i++)
            {
                if (i > 0)
                    cellList[i].BorderWidthLeft = 0;

                cellList[i].Padding = 5;
                cellList[i].NoWrap = true;
                cellList[i].HorizontalAlignment = Element.ALIGN_CENTER;
                cellList[i].VerticalAlignment = Element.ALIGN_MIDDLE;
                cellList[i].BorderWidthBottom = 0;
                table.AddCell(cellList[i]);
            }

            List<PdfPCell> list = new List<PdfPCell>()
            {
                new PdfPCell(new Phrase("身份证号", font)){ Colspan=1},
                new PdfPCell(new Phrase(CustomerInfo.IdCard??"---", font)){ Colspan=3 },
                new PdfPCell(new Phrase("紧急联系方式", font)){ Colspan=2 },
                new PdfPCell(new Phrase(CustomerInfo.TelePhone??"---------", font)){ Colspan=2 }
            };

            for (int i = 0; i < list.Count; i++)
            {
                if (i > 0)
                    list[i].BorderWidthLeft = 0;

                list[i].Padding = 5;
                list[i].Rowspan = 1;
                //list[i].SetLeading(1, 1.3f);
                list[i].HorizontalAlignment = Element.ALIGN_CENTER;

                list[i].BorderWidthBottom = 0;
                table.AddCell(list[i]);
            }
        }
        #endregion


        #region 报考内容
        /// <summary>
        /// 咨询报考
        /// </summary>
        /// <param name="document">pdf文档</param>
        /// <returns></returns>
        protected virtual void GetMajorTypeInfo()
        {

            if (OrderInfo.OrderCategory?.ToLower() == "servicecategory"||Config.Category?.ToLower() == "servicecategory")
            {
                //服务费
                base.GetMajorTypeInfo();
                return;
            }

            string lableText = "报考内容";

            PdfPCell cellExamInfo = new PdfPCell(new Phrase(lableText, font));
            cellExamInfo.Colspan = 1;
            cellExamInfo.Rowspan = 1;
            cellExamInfo.Padding = 5;
            cellExamInfo.BorderWidthBottom = 0;
            cellExamInfo.BorderWidthBottom = 0;
            cellExamInfo.HorizontalAlignment = Element.ALIGN_CENTER;
            cellExamInfo.VerticalAlignment = Element.ALIGN_MIDDLE;
            table.AddCell(cellExamInfo);

            string majors = string.Empty;
            if (OrderItemInfo.FirstSchoolMajors?.Count > 0)
                majors = string.Join("，", OrderItemInfo.FirstSchoolMajors);

            string level = string.Empty;
            if (OrderItemInfo.EduModeCode?.ToUpper() != "CRZZ")
                level = $@"层次：{OrderItemInfo.LevelName}；";


            string str = $"类型：{OrderItemInfo.EduModeName}；{level}专业：{majors}";
            var cell = new PdfPCell(new Phrase($"{str}", font));
            cell.Padding = 5;
            cell.Rowspan = 1;
            cell.Colspan = 7;
            cell.BorderWidthLeft = 0;
            cell.BorderWidthBottom = 0;
            cell.VerticalAlignment = Element.ALIGN_MIDDLE;
            // cell.SetLeading(1, 1.3f);
            table.AddCell(cell);
        }
        #endregion

        #region 缴费信息
        /// <summary>
        /// 缴费信息
        /// </summary>
        /// <param name="table"></param>
        /// <param name="pdf"></param>
        protected override void GetPayInfo()
        {


            if (OrderInfo.OrderCategory?.ToLower() == "servicecategory" || Config.Category?.ToLower() == "servicecategory")
            {
                //服务费
                base.GetPayInfo();
                return;
            }

            PdfPCell cellPayInfoInfo = new PdfPCell(new Phrase("缴费信息", font));
            cellPayInfoInfo.Colspan = 1;
            cellPayInfoInfo.Rowspan = 2;
            cellPayInfoInfo.BorderWidthBottom = 0;
            cellPayInfoInfo.HorizontalAlignment = Element.ALIGN_CENTER;
            cellPayInfoInfo.VerticalAlignment = Element.ALIGN_MIDDLE;
            table.AddCell(cellPayInfoInfo);


            string allAmount = String.Empty;

            //后续考虑此段代码写法
            if (OrderItemInfo.EduModeCode?.ToUpper() == "ZXKS")//自学考试
            {
                allAmount = $@"应缴费总金额：{ConvertToChineseAndLowerString(OrderInfo.OrderTotal)}。 其中含报考费、考前培训费和服务费";
            }
            else if (OrderItemInfo.EduModeCode?.ToUpper() == "TDXLSS")//同等学力申硕
            {
                allAmount = $@"应缴费总金额：{ConvertToChineseAndLowerString(OrderInfo.OrderTotal)}。 其中含学费和培训服务费";
            }
            else
            {
                if (OrderItemInfo.PayModel?.ToUpper() != "ZZJF")
                {
                    if (OrderItemInfo.EduModeCode?.ToUpper() == "CRGK")
                        allAmount = $"应缴费总金额：{ConvertToChineseAndLowerString(OrderInfo.OrderTotal)}  其中含学费和培训服务费";  //\n\n
                    else
                        allAmount = $"应缴费总金额：{ConvertToChineseAndLowerString(OrderInfo.OrderTotal)}  其中含学费和服务费。";
                }
                else
                {
                    if (OrderItemInfo.EduModeCode?.ToUpper() == "CRGK")
                        allAmount = $"应缴纳课程服务费总金额：{ConvertToChineseAndLowerString(OrderInfo.OrderTotal)}";  //\n\n
                    else
                        allAmount = $"应缴纳服务费总金额：{ConvertToChineseAndLowerString(OrderInfo.OrderTotal)}";
                }
            }

            List<PdfPCell> listExamInfoItems = new List<PdfPCell>()
            {
               new PdfPCell(new Phrase(allAmount, font)) { Rowspan = 1}
             };
            //欠费金额：*******元(¥*****)（说明：多次缴费账单展示）
            StringBuilder str = new StringBuilder();

            if (OrderInfo.TransferInAmount > 0)
                str.Append($"转入金额：{ConvertToChineseAndLowerString(OrderInfo.TransferInAmount)}");

            if (OrderInfo.TransferInAmount >= (decimal)OrderItemInfo.Amount / 100)
                str.Append($"缴费类型：（全款） ");
            else
                str.Append($"缴费类型：（部分款） ");

            str.Append($"缴费时间：{OrderInfo.CreateTime.ToString("yyyy-MM-dd")}");

            str.Append($"\n备注：{OrderInfo.TransferMessage}");
            if (OrderInfo.OrderType != "JZ")
            {
                foreach (var item in OrderInfo.ReceiptInfos)
                {
                    str.Append($"\n缴费金额：{ConvertToChineseAndLowerString(item.ThisPay)} " +
                                 $"缴费类型：({(item.ThisPay >= OrderInfo.AllNeedPay ? "全款" : "部分款")}) 缴费时间：{item.ReceiptTime}");
                }
            }

            str.Append($"\n欠费金额：{ConvertToChineseAndLowerString(OrderInfo.ArrearsAmount)}");
            listExamInfoItems.Add(new PdfPCell(new Phrase(str.ToString(), font)) { Rowspan = 1 });
            listExamInfoItems.ForEach(c =>
            {
                c.Padding = 5;
                //c.SetLeading(1, 1.3f);
                c.Colspan = 7;
                c.BorderWidthLeft = 0;
                c.BorderWidthBottom = 0;
                table.AddCell(c);
            });
        }
        #endregion

        #region 缴费协议
        protected virtual void GetNotic()
        {
            var cell = new PdfPCell(new Phrase("缴费协议", font))
            {
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment = Element.ALIGN_MIDDLE
            };
            cell.Colspan = 1;
            cell.Padding = 5;
            cell.BorderWidthRight = 0;
            table.AddCell(cell);

            Config.PayNotice = Config.PayNotice?.Replace("\"", "'") ?? "";

            if (Config.PayNotice.IndexOf("img") > 0)
            {
                Config.PayNotice = "暂不支持图片的展示，请删除图片";
            }
            using (StringReader sr = new StringReader(Config.PayNotice))
            {
                Phrase p = new Phrase(string.Empty, new Font(baseFont, 12));
                var elements = HtmlWorker.ParseToList(sr, null);
                //var elements = HtmlConverter.ConvertToElements(sr.ToString());
                foreach (IElement e in elements)
                    p.Add(e);

                var noticeCell = new PdfPCell(p);
                noticeCell.Colspan = 7;
                noticeCell.Padding = 5;
                noticeCell.SetLeading(1, 1.3f);
                table.AddCell(noticeCell);
            }

        }

        /// <summary>
        /// 学员签名
        /// </summary>
        /// <param name="isConfirm"></param>
        protected virtual void GetSign()
        {

            var sign = new Paragraph(new Chunk($"学员签字： ", font));

            var tempFont = new Font(baseFont, 10, 0, BaseColor.Black);
            string signDownload = "_________________";
            if (OrderInfo.OrderConfirmTime.HasValue)
            {
                signDownload = $"{CustomerInfo.Name} {((DateTime)OrderInfo.OrderConfirmTime).ToString("yyyy-MM-dd HH:mm:ss")}";
                tempFont.SetStyle("underline");
            }
            sign.Add(new Chunk(signDownload, tempFont));
            sign.SpacingAfter = 5;
            sign.Alignment = Element.ALIGN_RIGHT;
            document.Add(sign);
        }

        #endregion

        #region 加盖公章
        private void SetSeal()
        {
            if (string.IsNullOrWhiteSpace(FullPathSeal)) return;
            try
            {
                // FullPathSeal = "E:\\education\\feature_eduorder-2.1\\education.service\\modules\\ordering\\host\\Yyd.Ordering.HttpApi.Host\\bin\\Debug\\net6.0\\c.jpg";
                Image img = Image.GetInstance(FullPathSeal);

                var w = document.PageSize.Width - document.PageSize.Width / 3;
                var h = document.PageSize.Height - document.PageSize.Height / 4;
                if (document.PageSize.Height <= 500)
                {
                    h = document.PageSize.Height / 2;
                }
                img.SetAbsolutePosition(w, h);
                img.ScaleToFit(150, 150);
                //img.Left = 0;
                //img.Top = 0;
                document.Add(img);
            }
            catch (Exception e)
            {
                //throw new UserFriendlyException($"收据{ReceiptInfo.Number}电子凭证路径不存在!");
                //收据电子凭证路径如果不存在，则不加载公章，继续生成不带公章的电子凭证
                return;
            }
        }
        #endregion



        /// <summary>
        /// 写入Pdf内容
        /// </summary>
        /// <returns></returns>
        protected virtual void WritePdf()
        {
            GetHeader();
            GetCustomerInfo();

            GetMajorTypeInfo();
            GetPayInfo();
            SetSeal();
            GetNotic();
            document.Add(table);
            GetSign();

        }


        /// <summary>
        /// 获取写入的PDF文件流
        /// </summary>
        /// <returns></returns>
        public MemoryStream GetPdfStream()
        {
            MemoryStream ms = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            writer.CloseStream = false;
            writer.Open();
            document.Open();
            WritePdf();
            document.Close();
            ms.Position = 0;
            return ms;
        }
    }
}